package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.config.MyThreadConfig;
import com.atguigu.gulimall.cart.entity.CartItemVo;
import com.atguigu.gulimall.cart.entity.CartVo;
import com.atguigu.gulimall.cart.entity.SkuInfoVo;
import com.atguigu.gulimall.cart.entity.UserInfoTo;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Override
    public CartItemVo addToCart(Long skuId, Integer num) {
        BoundHashOperations<String,Object,Object> catOps = getCatOps();

        String res = (String) catOps.get(skuId.toString());
        if (StringUtils.isEmpty(res)){
            CartItemVo cartItemVo=new CartItemVo();
            //查询sku信息
            CompletableFuture<Void> skuInfoFuture = CompletableFuture.runAsync(() -> {
                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItemVo.setSkuId(skuInfo.getSkuId());
                cartItemVo.setPrice(skuInfo.getPrice());
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setTitle(skuInfo.getSkuSubtitle());
                cartItemVo.setCheck(true);
                cartItemVo.setCount(num);
            }, threadPoolExecutor);

            //查询sku销售属性
            CompletableFuture<Void> skuSaleAttrValueFuture = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValue = productFeignService.getSkuSaleAttrValue(skuId);
                cartItemVo.setSkuAttr(skuSaleAttrValue);
            }, threadPoolExecutor);

            try {
                CompletableFuture.allOf(skuInfoFuture,skuSaleAttrValueFuture).get();
            } catch (InterruptedException | ExecutionException e) {
                log.error("添加购物车失败");
                return cartItemVo;
            }
            catOps.put(skuId.toString(), JSON.toJSONString(cartItemVo));
            return cartItemVo;
        }else {
            CartItemVo cartItem=JSON.parseObject(res,CartItemVo.class);
            cartItem.setCount(cartItem.getCount()+num);
            catOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> catOps = getCatOps();
        String s = (String) catOps.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(s, CartItemVo.class);
        return cartItemVo;
    }

    @Override
    public CartVo getCart() {
        CartVo cartVo=new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //1 已经登录
        if (userInfoTo.getUserId()!=null){
            String key=CartConstant.CART_PREFIX+userInfoTo.getUserId();

            String temporaryKey= CartConstant.CART_PREFIX + userInfoTo.getUserKey();

            //1.1整合临时数据到用户购物车
            List<CartItemVo> redisCartItem = getRedisCartItem(temporaryKey);
            if (!CollectionUtils.isEmpty(redisCartItem)){
                for (CartItemVo cartItemVo:redisCartItem) {
                    addToCart(cartItemVo.getSkuId(),cartItemVo.getCount());
                }
            }

            //删除key
            deleteRedisCartItem(temporaryKey);

            //查询购物车
            List<CartItemVo> redisCartItemUser = getRedisCartItem(key);
            cartVo.setItems(redisCartItemUser);
        }else {
            //2用户未登录
            String key=CartConstant.CART_PREFIX+userInfoTo.getUserKey();
            List<CartItemVo> redisCartItem = getRedisCartItem(key);
            cartVo.setItems(redisCartItem);
        }
        return cartVo;
    }

    @Override
    public void deleteIdCartInfo(Integer skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCatOps();
        cartOps.delete(skuId);
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        //查询购物车里面的商品
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        //序列化存入redis中
        String redisValue = JSON.toJSONString(cartItem);

        BoundHashOperations<String, Object, Object> cartOps = getCatOps();
        cartOps.put(skuId.toString(),redisValue);


    }

    @Override
    public void checkItem(Long skuId, Integer checked) {
        //查询购物车里面的商品
        CartItemVo cartItem = getCartItem(skuId);
        //修改商品状态
        cartItem.setCheck(checked == 1?true:false);

        //序列化存入redis中
        String redisValue = JSON.toJSONString(cartItem);

        BoundHashOperations<String, Object, Object> cartOps = getCatOps();
        cartOps.put(skuId.toString(),redisValue);
    }

    @Override
    public List<CartItemVo> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()==null){
            return null;
        }else {
           String key = CartConstant.CART_PREFIX+userInfoTo.getUserId();

           //获取用户购物车信息
            List<CartItemVo> redisCartItem = getRedisCartItem(key);

            //过滤已勾选商品
            if (CollectionUtils.isEmpty(redisCartItem)){
                return null;
            }
            List<CartItemVo> collect = redisCartItem
                    .stream()
                    .filter(CartItemVo::getCheck)
                    .map(e->{
                        //获取最新价格
                       e.setPrice(productFeignService.getPrice(e.getSkuId()));
                       return e;
                    })
                    .collect(Collectors.toList());
            return collect;
        }
    }


    private void deleteRedisCartItem(String key){
       redisTemplate.delete(key);
    }

    private List<CartItemVo> getRedisCartItem(String key){
        List<CartItemVo> collect=new ArrayList<>();
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(key);
        List<Object> values = hashOps.values();
        if (!CollectionUtils.isEmpty(values)){
             collect = values.stream().map((obj) -> {
                String s = (String) obj;
                return JSON.parseObject(s, CartItemVo.class);
            }).collect(Collectors.toList());
        }
        return collect;
    }

    public BoundHashOperations<String,Object,Object> getCatOps(){
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String key="";
        if (userInfoTo.getUserId()!=null){
           // log.info("用户已经登录，设置用户购物车key");
            key=CartConstant.CART_PREFIX+userInfoTo.getUserId();
        }else {
         //   log.info("用户未登录，设置临时购物车key");
            key=CartConstant.CART_PREFIX+userInfoTo.getUserKey();
        }
        return redisTemplate.boundHashOps(key);
    }
}
